package cn.how2go.api.controller;


import cn.how2go.api.common.*;
import cn.how2go.api.entity.*;
import cn.how2go.api.service.DeviceService;
import cn.how2go.api.service.PersonService;
import cn.how2go.api.service.WarningService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2020-05-31
 */
@Api(value = "告警",description = "告警信息的管理")
@RestController
@RequestMapping("/api/warning")
public class WarningController {
    @Autowired
    private WarningService warningService;

    @Autowired
    private PersonService personService;

    @Autowired
    private DeviceService deviceService;

    @ApiOperation(value="查询告警信息列表", notes="")
    @RequestMapping(value = "listWarning", method = RequestMethod.GET)
    public CommonResult listWarning(){
        EntityWrapper<Warning> entityWrapper = new EntityWrapper<>();
        entityWrapper.orderBy("RecordTime",false);
        List<Warning> list = warningService.selectList(entityWrapper);
        return CommonResult.success(list);
    }

    @ApiOperation(value="分页查询告警历史列表", notes="")
    @RequestMapping(value = "pageOldWarnning", method = RequestMethod.POST)
    public Pagination pageOldWarnning(@RequestBody PageParam param){
        Pagination<UserWarnning> pagination = new Pagination<>(param.getPage(),param.getSize(),null,null);
        List<UserWarnning> all = allOldWarnning();;
        //共有数据量
        Integer count = all.size();
        //算出共有多少页
        Integer total = (count%param.getSize()==0)?count/param.getSize():count/param.getSize()+1;
        pagination.setTotal(total);
        //当前页的数据
        List<UserWarnning> result = new ArrayList<>();
        //开始取数据的标记
        Integer offset = pagination.offset();
        if((offset+param.getSize())>all.size()) {
            for (int i = offset; i < all.size(); i++) {
                result.add(all.get(i));
            }
        }else{
            for (int i = offset; i < offset+param.getSize(); i++) {
                result.add(all.get(i));
            }
        }
        pagination.setItems(result);
        return pagination;
    }

    @ApiOperation(value="分页查询新告警列表", notes="")
    @RequestMapping(value = "pageUserWarnning", method = RequestMethod.POST)
    public Pagination pageUserWarnning(@RequestBody PageParam param){
        Pagination<UserWarnning> pagination = new Pagination<>(param.getPage(),param.getSize(),null,null);
        List<UserWarnning> all = allUserWarnning();;
        //共有数据量
        Integer count = all.size();
        //算出共有多少页
        Integer total = (count%param.getSize()==0)?count/param.getSize():count/param.getSize()+1;
        pagination.setTotal(total);
        //当前页的数据
        List<UserWarnning> result = new ArrayList<>();
        //开始取数据的标记
        Integer offset = pagination.offset();
        if((offset+param.getSize())>all.size()) {
            for (int i = offset; i < all.size(); i++) {
                result.add(all.get(i));
            }
        }else{
            for (int i = offset; i < offset+param.getSize(); i++) {
                result.add(all.get(i));
            }
        }
        pagination.setItems(result);
        return pagination;
    }

    private List<UserWarnning> allOldWarnning(){
        List<UserWarnning> userWarnningList= new ArrayList<>();
        List<UserWarnning> list =  warningService.getListUserWarnning(true);
        for(UserWarnning bean : list){
            UserWarnning temp = bean;
            temp.setTypeName(getTypeName(bean.getType()));
            userWarnningList.add(temp);
        }
        return userWarnningList;
    }

    private List<UserWarnning> allUserWarnning(){
        List<UserWarnning> userWarnningList= new ArrayList<>();
        List<UserWarnning> list =  warningService.getListUserWarnning(false);
        for(UserWarnning bean : list){
            UserWarnning temp = bean;
            temp.setTypeName(getTypeName(bean.getType()));
            userWarnningList.add(temp);
            temp.setProcessTime(bean.getProcessTime());
        }
        return userWarnningList;
    }

    @ApiOperation(value="查询新告警信息列表", notes="")
    @RequestMapping(value = "listNewWarning", method = RequestMethod.GET)
    public CommonResult listNewWarning(){
        List<UserWarnning> userWarnningList = allUserWarnning();
        return CommonResult.success(userWarnningList);
    }

    private String getPersonName(String id){
        String name = "";
        EntityWrapper<Person> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("id",id);
        entityWrapper.last("limit 1");
        Person person = personService.selectOne(entityWrapper);
        name = person.getName();
        return name==null?"未绑定":name;
    }

    private String getTypeName(Integer warnning){
        String type = "";
        switch(warnning) {
            case 1:
                type = "电子围栏禁入告警";
                break;
            case 2:
                type = "电子围栏禁出告警";
                break;
            case 3:
                type = "体征异常告警";
                break;
            case 4:
                type = "工器佩戴";
                break;
            case 5:
                type = "高挂低用";
                break;
            case 6:
                type = "SOS报警";
                break;
            case 7:
                type = "跌落";
                break;
            case 8:
                type = "近电提醒";
                break;
            case 9:
                type = "离开近电";
                break;
            case 10:
                type = "安全帽未佩戴";
                break;
            default:
                type="";
        }
        return type;
    }

    @ApiOperation(value="根据时间查询告警信息列表", notes="")
    @RequestMapping(value = "listWarningByTime", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "startTime",value = "开始时间，数据类型：yyyy-MM-dd HH:mm:ss", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "endTime", value = "结束时间，数据类型：yyyy-MM-dd HH:mm:ss", required = false, dataType = "String"),
    })
    public CommonResult listWarningByTime(
            @RequestParam(value = "startTime", required = true) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime){
        EntityWrapper<Warning> entityWrapper = new EntityWrapper<>();
        entityWrapper.orderBy("RecordTime",false);
        entityWrapper.ge("RecordTime",startTime);
        if(endTime!=null)
            entityWrapper.le("RecordTime",endTime);
        List<Warning> list = warningService.selectList(entityWrapper);
        return CommonResult.success(list);
    }

    @ApiOperation(value="处理告警信息", notes="处理告警信息，ProcessTime后台修改")
    @RequestMapping(value = "editWarring", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "ID", value = "告警编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "Processor",value = "处理/取消此告警事件人员的ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "State", value = "此告警事件的状态：0： 未处理，等待处理1： 已经成功处理2： 已取消", required = true, dataType = "int"),
    })
    public CommonResult editWarring(
            @RequestParam(value = "ID", required = true) String id,
            @RequestParam(value = "Processor", required = true) String processor,
            @RequestParam(value = "State", required = false) int state){
        Warning bean = new Warning();
        bean.setProcessTime(new Date());
        bean.setProcessor(processor);
        bean.setState(state);
        EntityWrapper<Warning> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",id);
        boolean flag = warningService.update(bean,entityWrapper);
        if(!flag){
            return CommonResult.fail("修改失败");
        }
        return CommonResult.success(bean);
    }

    @ApiOperation(value="处理告警信息", notes="处理告警信息，ProcessTime后台修改")
    @RequestMapping(value = "doWarning", method = RequestMethod.POST)
    public CommonResult doWarning(@RequestBody WarningParam param){
        Warning bean = new Warning();
        bean.setProcessTime(new Date());
        bean.setProcessor("");
        bean.setState(param.getState());
        EntityWrapper<Warning> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",param.getId());
        boolean flag = warningService.update(bean,entityWrapper);
        if(!flag){
            return CommonResult.fail("修改失败");
        }
        return CommonResult.success(bean);
    }

    @ApiOperation(value="主页状态信息", notes="")
    @RequestMapping(value = "mainInfo", method = RequestMethod.GET)
    public CommonResult mainInfo(){
        MainInfo bean = new MainInfo();
        EntityWrapper<Person> personEntityWrapper = new EntityWrapper<>();
        List<Person> personList = personService.selectList(personEntityWrapper);
        bean.setTotal(personList.size());
        EntityWrapper<Device> deviceEntityWrapper = new EntityWrapper<>();
        deviceEntityWrapper.eq("type",1);
        deviceEntityWrapper.eq("working",1);
        deviceEntityWrapper.ne("state",3);
        List<Device> devices = deviceService.selectList(deviceEntityWrapper);
        bean.setInline(devices.size());

        List<WarningCount> warningCounts = warningService.countByType();
        bean.setWwei(0);
        bean.setWsos(0);
        bean.setWgong(0);
        bean.setWtin(0);
        for(WarningCount warningCount:warningCounts){
            if(warningCount.getType()==1){
                bean.setWwei(bean.getWwei()+warningCount.getShu());
            }
            if(warningCount.getType()==2){
                bean.setWwei(bean.getWwei()+warningCount.getShu());
            }
            if(warningCount.getType()==6){
                bean.setWsos(bean.getWsos()+warningCount.getShu());
            }
            if(warningCount.getType()==7){
                bean.setWsos(bean.getWsos()+warningCount.getShu());
            }
            if(warningCount.getType()==3){
                bean.setWtin(warningCount.getShu());
            }
            if(warningCount.getType()==4){
                bean.setWgong(bean.getWgong()+warningCount.getShu());
            }
            if(warningCount.getType()==5){
                bean.setWgong(bean.getWgong()+warningCount.getShu());
            }
            if(warningCount.getType()==8){
                bean.setWgong(bean.getWgong()+warningCount.getShu());
            }
            if(warningCount.getType()==9){
                bean.setWgong(bean.getWgong()+warningCount.getShu());
            }
            if(warningCount.getType()==10){
                bean.setWgong(bean.getWgong()+warningCount.getShu());
            }
        }

        return CommonResult.success(bean);
    }

    @ApiOperation(value="Safe页状态信息", notes="")
    @RequestMapping(value = "safeInfo", method = RequestMethod.GET)
    public CommonResult safeInfo(){
        AllWarning bean = new AllWarning();

        List<WarningCount> warningCounts = warningService.countByType();
        bean.setTizheng(0);
        bean.setGongju(0);
        bean.setWeilan(0);
        bean.setDieluo(0);
        bean.setSos(0);
        for(WarningCount warningCount:warningCounts){
            if(warningCount.getType()==1){
                bean.setWeilan(bean.getWeilan()+warningCount.getShu());
            }
            if(warningCount.getType()==2){
                bean.setWeilan(bean.getWeilan()+warningCount.getShu());
            }
            if(warningCount.getType()==6){
                bean.setSos(bean.getSos()+warningCount.getShu());
            }
            if(warningCount.getType()==7){
                bean.setDieluo(bean.getDieluo()+warningCount.getShu());
            }
            if(warningCount.getType()==3){
                bean.setTizheng(warningCount.getShu());
            }
            if(warningCount.getType()==4){
                bean.setGongju(bean.getGongju()+warningCount.getShu());
            }
            if(warningCount.getType()==5){
                bean.setGongju(bean.getGongju()+warningCount.getShu());
            }
            if(warningCount.getType()==8){
                bean.setGongju(bean.getGongju()+warningCount.getShu());
            }
            if(warningCount.getType()==9){
                bean.setGongju(bean.getGongju()+warningCount.getShu());
            }
            if(warningCount.getType()==10){
                bean.setGongju(bean.getGongju()+warningCount.getShu());
            }
        }

        return CommonResult.success(bean);
    }

    @ApiOperation(value="批量操作", notes="")
    @RequestMapping(value = "plOp", method = RequestMethod.GET)
    public CommonResult plOp(@RequestParam(value = "op", required = true) Integer op){
        Warning bean = new Warning();
        bean.setProcessor("-");
        bean.setProcessTime(new Date());
        bean.setState(op);
        EntityWrapper<Warning> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("state",0);
        entityWrapper.eq("alarm",1);
        warningService.update(bean,entityWrapper);
        return CommonResult.success(null);
    }
}

